package com.ubaer.zsycz.ui.base.activity;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lsw.dialog.DialogProgress;
import com.lsw.shareUser.ShareUserInfoUtil;
import com.lsw.util.AppManager;
import com.lsw.util.Helper;
import com.lsw.util.HideSoftKeyboardUtil;
import com.lsw.util.StatusBarCompat;
import com.ubaer.zsycz.MyApplication;
import com.ubaer.zsycz.R;
import com.ubaer.zsycz.inject.components.ActivityComponent;
import com.ubaer.zsycz.inject.components.DaggerActivityComponent;
import com.ubaer.zsycz.inject.modules.ActivityModule;
import com.ubaer.zsycz.ui.activity.LoginActivity;
import com.ubaer.zsycz.ui.base.presenter.IPresenter;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.inject.Inject;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * author：lsw
 */
public abstract class TitleBarActivity<T extends IPresenter> extends FragmentActivity {

    public static String BUNDLE = "BUNDLE";
    //拨打电话权限
    String[] p = {android.Manifest.permission.CALL_PHONE};
    private String number = "15708447033";
    protected Toast mToast;
    /**
     * 左边的按钮 默认显示
     */
    protected ImageView btnLeft;
    /**
     * 带文字的按钮
     */
    protected Button btnLeftText;
    /**
     * 标题栏 默认显示
     */
    public TextView tvTitle;
    public TextView tvTitle_english;
    /**
     * 最右边的按钮 默认隐藏
     */
    protected ImageView btnRight, btnRight2;
    /**
     * 从右边算第2个按钮 默认隐藏
     */
    protected Button btnRightText;

    protected String TAG = this.getClass().getName();
    /**
     * 内容区父控件
     */
    protected ViewGroup contentLayout;
    /**
     * 顶部标题栏
     */
    protected View actionBarView;
    protected Activity mContext;

    /**
     * 进度条
     */
    protected DialogProgress progress;


    protected View layoutAll;

    //////////////////////////////////////
    @Inject
    protected T mPresenter;
    protected Unbinder unbinder;

    protected ActivityComponent mActivityComponent;

    //注入
    protected abstract void initInjector();

    //初始化事件和数据
    protected abstract void initEventAndData();

    @Override
    protected final void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        initBaseConfig();
        setContentView(R.layout.baseactivity_bar);
        Helper.statusBarLightMode(this);
        AppManager.getAppManager().addActivity(this);
        mActivityComponent = DaggerActivityComponent.builder().appComponent(MyApplication.getAppComponent())
                .activityModule(new ActivityModule(this)).build();
        initInjector();
        if (mPresenter != null) mPresenter.attachView(this, this);
        progress = new DialogProgress(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.colorPrimary));
        }
        layoutAll = findViewById(R.id.bg);
        mContext = this;
        setActionBarLayout();
        setActionBarDetail();
        int resource = setContentLayoutView();
        if (resource != 0) {
            View contentView = getLayoutInflater().inflate(resource, null);
            contentLayout.addView(contentView, new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            // 点击EditText以外的区域或者控件隐藏软键盘
            HideSoftKeyboardUtil.setupUI(contentView, (Activity) mContext);
        }
        unbinder = ButterKnife.bind(this);
        initEventAndData();
    }

    private void initBaseConfig() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        SetStatusBarColor();
    }

    /**
     * 着色状态栏（4.4以上系统有效）
     */
    protected void SetStatusBarColor() {
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorAccent));
    }

    /**
     * 着色状态栏（4.4以上系统有效）
     */
    protected void SetStatusBarColor(int color) {
        StatusBarCompat.setStatusBarColor(this, color);
    }

    /**
     * 沉浸状态栏（4.4以上系统有效）
     */
    protected void SetTranslanteBar() {
        StatusBarCompat.translucentStatusBar(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.detachView();
        unbinder.unbind();
        AppManager.getAppManager().finishActivity(this);
    }

    /**
     * 设置内容区
     *
     * @return
     */
    protected abstract int setContentLayoutView();

    /**
     * 需要处理actionbar的细节显示 左边按钮和右边按钮的图片资源 中间的editText是否显示
     */
    protected abstract void setActionBarDetail();

    /**
     * 自定义actionBar视图
     *
     * @param
     */
    private void setActionBarLayout() {
        tvTitle = (TextView) findViewById(R.id.action_bar_title);
        tvTitle_english = (TextView) findViewById(R.id.action_bar_title_english);
        // 设置标题
        tvTitle.setText(getTitle());
        // 顶部标题栏
        actionBarView = findViewById(R.id.action_bar);
        // 左边图片按钮，默认显示
        btnLeft = (ImageView) findViewById(R.id.action_bar_left_btn);
        btnLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 左边按钮点击，默认结束当前视图
                hideSoftInput(view);
                finish();
            }
        });
        // 左边文字按钮,默认隐藏
        btnLeftText = (Button) findViewById(R.id.action_bar_left_btn_text);
        // 最右边按钮，默认隐藏
        btnRight = (ImageView) findViewById(R.id.right_btn);
        // 从右边起，第二图片按钮
        btnRight2 = (ImageView) findViewById(R.id.right_btn2);

        // 从右边数第2个按钮，默认隐藏
        btnRightText = (Button) findViewById(R.id.action_bar_right_btn_text);
        // cb_action_bar_right_btn_text=(CheckBox)findViewById(R.id.cb_action_bar_right_btn_text);
        // 底部内容视图，子类添加视图进去
        contentLayout = (ViewGroup) findViewById(R.id.frame_layout);
    }


    public void calls(String phone) {
        this.number = phone;
        if (!checkPermissions(p)) {
            requestPermission(p, 10);
        } else {
            if (!number.equals(""))
                call(number);
        }
    }


    //用intent启动拨打电话
    public void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        try {
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏输入法
     */
    public void hideSoftInput(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
        }
    }

    /**
     * 如果输入法在窗口上已经显示，则隐藏，反之则显示
     */
    public void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    //输入法是否显示着
    public static boolean KeyBoard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        return imm.isActive();//isOpen若返回true，则表示输入法打开
    }

    /**
     * 弹出输入法
     *
     * @param v
     */
    public static void ShowKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);

    }

    public void showToast(String msg) {
        if (mToast == null) {
            mToast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(msg);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    /**
     * 密码校验，数字或者小写字母或者大写字母
     *
     * @param pass
     * @return
     */
    public boolean isValidePassword(String pass) {
        Pattern pattern = Pattern.compile("^[A-Za-z0-9]{6,16}$");
        Matcher matcher = pattern.matcher(pass);
        return matcher.matches();
    }


//    /**
//     * 进入主页
//     */
//    public void openMain() {
//        Intent intent = new Intent(context, MainActivity.class);
//        startActivity(intent);
//        ((Activity) context).finish();
//    }
//

    /**
     * 用户单点登录
     */
    public void OpenLogin() {
        ShareUserInfoUtil.getInstance(mContext).clearCache();
        Intent intent = new Intent(mContext, LoginActivity.class);
        startActivity(intent);
        finish();
        AppManager.getAppManager().finishAllActivity();
    }

    /**
     * 注销退到登录页
     *
     * @param isfinsh 是否关闭当前页
     */
    public void openLogin(boolean isfinsh) {
//        Intent intent = new Intent(context, LoginActivity.class);
//        startActivity(intent);
//        if (isfinsh) {
//            ((Activity) context).finish();
//        }
    }

    /**
     * 显示进度框
     */
    public void showProgressDialog() {
        if (!progress.isShowing())
            progress.show();
    }


    /**
     * 取消进度框
     */
    public void cancelProgressDialog() {
        if (progress.isShowing())
            progress.dismiss();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            // 点击一次返回按钮
//            setResultCustom();
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 请求权限
     *
     * @param permissions 请求的权限
     * @param requestCode 请求权限的请求码
     */
    public void requestPermission(String[] permissions, int requestCode) {
        this.REQUEST_CODE_PERMISSION = requestCode;
        if (requestCode == 10) {
            if (!number.equals(""))
                call(number);
            return;
        }
        if (checkPermissions(permissions)) {
            permissionSuccess(REQUEST_CODE_PERMISSION);
        } else {
            List<String> needPermissions = getDeniedPermissions(permissions);
            ActivityCompat.requestPermissions(this, needPermissions.toArray(new String[needPermissions.size()]), REQUEST_CODE_PERMISSION);
        }

    }

    /**
     * 检测所有的权限是否都已授权
     *
     * @param permissions
     * @return
     */
    public boolean checkPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }

        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     */
    private List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                needRequestPermissionList.add(permission);
            }
        }
        return needRequestPermissionList;
    }

    private int REQUEST_CODE_PERMISSION = 0x00099;

    /**
     * 系统请求权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.i("http=", "activityrequestCode====" + requestCode);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (verifyPermissions(grantResults)) {
                permissionSuccess(REQUEST_CODE_PERMISSION);
            } else {
                permissionFail(REQUEST_CODE_PERMISSION);
                showTipsDialog();
            }
        }
    }

    /**
     * 获取权限成功
     *
     * @param requestCode
     */
    public void permissionSuccess(int requestCode) {

    }

    /**
     * 权限获取失败
     *
     * @param requestCode
     */
    public void permissionFail(int requestCode) {

    }

    /**
     * 确认所有的权限是否都已授权
     *
     * @param grantResults
     * @return
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示提示对话框
     */
    public void showTipsDialog() {
        new android.support.v7.app.AlertDialog.Builder(this)
                .setTitle("提示信息")
                .setMessage("当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                }).show();
    }

    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    /**
     * 字体不随系统设置改变
     *
     * @return
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

}
